<?php

namespace App\Dao;

use App\Model\UserBlacklist;
use Hyperf\Context\ApplicationContext;

class UserBlacklistDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }


    // 查询用户自己拉黑的用户
    public function getBlacklist($uid)
    {
        // $sql = "SELECT a.uid,a.uid,a.black_uid,a.black_time,b.nickname,b.head_image FROM {$this->table} a LEFT JOIN {$this->tableU} b ON a.black_uid=b.id WHERE a.uid = ? AND a.black_status=0 ORDER BY a.black_time DESC";
        // $pd = $this->createCommand($sql);
        // $pd->execute(array($uid));
        // $list = $pd->fetchAll(PDO::FETCH_ASSOC);
        $list = UserBlacklist::query()
            ->select(['tb_user_blacklist.uid', 'tb_user_blacklist.black_uid', 'tb_user_blacklist.black_time', 'tb_user.nickname', 'tb_user.head_image'])
            ->leftJoin('tb_user', 'tb_user.id', '=', 'tb_user_blacklist.black_uid')
            ->where('tb_user_blacklist.uid', $uid)
            ->where('tb_user_blacklist.black_status', 0)
            ->orderBy('tb_user_blacklist.black_time', 'desc')
            ->get()->toArray();
        return $list;
    }


    /**
     * 获取拉黑我的uid
     * @param $uid
     * @return array
     */
    public function getBlackUids($uid)
    {
        $rs1 = UserBlacklist::getBlackBarUids($uid);
        $rs2 = UserBlacklist::getBlackFooUids($uid);
        $black_list = array_unique(array_merge($rs1, $rs2));
        return $black_list;
    }


    /**
     * 是否在对方黑名单中
     * @param $uid
     * @param $black_uid
     * @return bool
     */
    public function inBlackList($uid, $black_uid)
    {
        // $sql = "SELECT id FROM {$this->table} WHERE ((uid=$uid AND black_uid=$black_uid) OR (uid=$black_uid AND black_uid=$uid)) AND black_status=0";
        // $rs = $this->findOne($sql);
        // return !empty($rs);
        return UserBlacklist::query()->where('black_status', 0)->where(function ($query) use ($uid, $black_uid) {
            $query->where('uid', $uid)->where('black_uid', $black_uid);
        })->orWhere(function ($query) use ($uid, $black_uid) {
            $query->where('uid', $black_uid)->where('black_uid', $uid);
        })->exists();

    }


}